package com.aaa.gateway;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;

/**
 * sentinel控流规则
 * sentinel使用gateway全局过滤器filter对请求进行拦截，判断是否需要进行限流，熔断，热点操作
 *sentinel工作原理:先对资源配置规则,请求到达服务器端后,sentinel根据规则对请求进行熔断
 *gateway工作原理:拦截请求判断请求进行转发
 */

@Component
public class FlowSentinelGatewayConfigur {
    //初始化拦截器,拦截请求
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE-1)
    public GlobalFilter sentinelGatewayFilter(){
        return new SentinelGatewayFilter();
    }
    /*
    * 限流规则
    * */
    @PostConstruct
    public void setFlowRules(){
        //GatewayFlowRule:gateway限流规则
        //资源:gateway中的路由
        GatewayFlowRule flowRule=new GatewayFlowRule("book");
        flowRule.setGrade(1);//阈值类型:1 qbs
        flowRule.setCount(5);//单机阈值
        flowRule.setIntervalSec(10);//窗口时间
        //不重复
        HashSet<GatewayFlowRule> set=new HashSet<>();
        set.add(flowRule);
        //添加到规则中
        GatewayRuleManager.loadRules(set);
    }














}
